<template>
  <div class="userInfo">
    <div class="el-form-box">
      <!-- :rules="rules" -->
      <el-form
        ref="userInfo"
        :model="userInfo"
        label-width="100px"
        size="small"
        label-position="right"
        :rules="rules"
      >
        <el-form-item label="头像：">
          <div class="logo-box">
            <img class="logo" :src="userInfo.avatar">
            <!-- :action="uploadImgUrl"
              :on-success="getImgUrl" -->
            <el-upload
              class="upload-demo"
              :show-file-list="false"
              :action="UploadUrl()"
              :before-upload="beforeAvatarUpload"
              :on-success="getImgUrl"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="userInfo.userName" />
        </el-form-item>
        <el-form-item label="密码：">
          <el-input
            v-model="userInfo.password"
            type="password"
            readonly
            disabled
          />
          <a
            href="javascript:void(0);"
            class="changePsd"
            @click="changePassword"
          >修改密码</a>
        </el-form-item>
        <el-form-item label="昵称" prop="nick">
          <el-input v-model="userInfo.nick" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="userInfo.mobile" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userInfo.email" />
        </el-form-item>
        <el-form-item label="QQ" prop="qq">
          <el-input v-model="userInfo.qq" />
        </el-form-item>
      </el-form>
      <!-- 修改密码弹框 -->
      <el-dialog
        title="修改密码"
        :visible.sync="dialogVisible"
        width="480px"
        :close-on-click-modal="false"
      >
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          status-icon
          :rules="rules"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="输入旧密码" prop="oldPass">
            <el-input
              v-model="ruleForm.oldPass"
              type="password"
              autocomplete="off"
            />
          </el-form-item>
          <el-form-item label="输入新密码" prop="pass">
            <el-input
              v-model="ruleForm.pass"
              type="password"
              autocomplete="off"
            />
          </el-form-item>
          <el-form-item label="重复密码" prop="checkPass">
            <el-input
              v-model="ruleForm.checkPass"
              type="password"
              autocomplete="off"
            />
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="saveChange">确认修改</el-button>
          <el-button @click="dialogVisible = false">返回</el-button>
        </span>
      </el-dialog>
      <!-- 保存按钮 -->
      <div style="width: 645px; float: right; text-align: center">
        <el-button
          size="small"
          type="primary"
          style="width: 100px"
          @click.native="updateuserInfo('userInfo')"
        >保存</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { validWords, validQQ, validEmail, validMobile } from '@/utils/validate' // 数据校验
import { mapGetters } from 'vuex'
import { getUserInfo, updateSysUser, changePassword } from '@/api/user'
export default {
  data() {
    // 数据校验
    const validatePass2 = (rule, value, callback) => {
      if (value !== this.ruleForm.pass) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    const validateUsername = (rule, value, callback) => {
      if (!validWords(value)) {
        callback(new Error('用户名由6-20位的字母数字下划线组成！！'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (!validWords(value)) {
        callback(new Error('密码由6-20位的字母数字下划线组成！！'))
      } else {
        callback()
      }
    }
    const validateNick = (rule, value, callback) => {
      if (!/^.{3,10}$/.test(value)) {
        callback(new Error('昵称为3-10个字符！！'))
      } else {
        callback()
      }
    }
    const validateMobile = (rule, value, callback) => {
      if (!validMobile(value)) {
        callback(new Error('电话号码格式不合法！！'))
      } else {
        callback()
      }
    }
    const validateEmail = (rule, value, callback) => {
      if (!validEmail(value)) {
        callback(new Error('邮箱格式不合法！！'))
      } else {
        callback()
      }
    }
    const validateQq = (rule, value, callback) => {
      if (!validQQ(value)) {
        callback(new Error('QQ号格式不合法！！'))
      } else {
        callback()
      }
    }
    return {
      dialogVisible: false,
      uploadImgUrl: '',
      userInfo: {
        id: undefined,
        userName: 'lzpisnb',
        password: 'lzpisnb',
        nick: '隔壁老龙',
        mobile: '15115282455',
        email: 'longzipeng@foxmail.com',
        qq: '1739028870',
        avatar: ''
      },
      ruleForm: {
        oldPass: '',
        pass: '',
        checkPass: ''
      },
      rules: {
        pass: [{ validator: validatePassword, trigger: 'blur' }],
        checkPass: [{ validator: validatePass2, trigger: 'blur' }],
        oldPass: [{ validator: validatePassword, trigger: 'blur' }],
        userName: [{ required: true, message: '', validator: validateUsername }],
        password: [{ required: true, message: '', validator: validatePassword }],
        nick: [{ required: true, message: '', validator: validateNick }],
        mobile: [{ required: true, message: '', validator: validateMobile }],
        email: [{ required: true, message: '', validator: validateEmail }],
        qq: [{ required: true, message: '', validator: validateQq }]
      }
    }
  },
  computed: {
    ...mapGetters([
      'token'
    ])
  },
  created() {
    this.getUserInfo()
  },
  methods: {
    saveChange() {
      this.$refs['userInfo'].validate((valid) => {
        if (valid) {
          changePassword({ id: this.userInfo.id,
            oldPassword: this.ruleForm.oldPass,
            newPassword: this.ruleForm.pass }).then((response) => {
            if (response.code === '200') {
              this.$notify({
                title: '提示',
                message: response.message,
                type: 'success',
                duration: 2000
              })
              this.logout()
            }
          })
        }
      })
    },
    updateuserInfo() {
      this.$refs['userInfo'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.userInfo)
          this.userInfo.password = undefined
          updateSysUser(tempData).then((response) => {
            if (response.code === '200') {
              this.$notify({
                title: '提示',
                message: '用户信息修改成功，请重新登录！！',
                type: 'success',
                duration: 2000
              })
              this.logout()
            }
          })
        }
      })
    },
    changePassword() {
      this.dialogVisible = true
    },
    UploadUrl() {
      return process.env.VUE_APP_BASE_API + '/file/upload_to_avatars'
    },
    beforeAvatarUpload(file) {
      console.log(file.type)
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif' || file.type === 'image/jpg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG、PNG、GIF 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    getUserInfo() {
      getUserInfo(this.token).then(response => {
        if (response.code === '200') {
          this.userInfo = response.data
        }
      })
    },
    getImgUrl(response) {
      if (response.code === '200') {
        this.userInfo.avatar = response.data
      } else {
        this.userInfo.avatar = response
      }
    },
    async logout() {
      await this.$store.dispatch('user/logout')
      this.$router.push(`/login?redirect=${this.$route.fullPath}`)
    }
  }
}
</script>

<style lang="scss" scoped>
.userInfo {
  ::v-deep .el-form-box {
    width: 45%;
    margin: 20px 0;
    .logo-box {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      margin-bottom: 10px;
      .logo {
        margin-bottom: 10px;
        width: 110px;
        height: 110px;
        display: block;
        border-radius: 50%;
        background: #ffffff;
      }
    }
  }
  .changePsd {
    text-decoration: none;
    color: #0066cc;
    position: absolute;
    right: -70px;
  }
  ::v-deep .el-dialog {
    .el-dialog__header {
      border-bottom: 1px solid #ccc;
      background-color: #649bee;
      color: white !important;
    }
    .el-dialog__body {
      padding: 30px 20px 10px;
    }
  }
}
</style>
